
import * as XLSX from 'xlsx';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Button, message, Modal } from 'antd';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
import CommandDrawer from './components/CommandDrawer';
import CopyCommandForm from './components/CopyCommandForm';
import EditCateForm from './components/EditCateForm';
import PromoteDrawer from './components/PromoteDrawer';
import {
  dealCommands,
  delayCommandTime,
  deleteDyCommand,
  dyCpsCommands,
  getStoreCate,
  saveStoreCate,
  saveSubChannelPercent,
} from './service';
import formatDateForExport from '@/utils/formatDateForExport';

const handleSaveCommand = async (selectedRows: any) => {
  const hide = message.loading('正在更新');
  try {
    const rsp = await dealCommands({ ...selectedRows });
    if (rsp.code === 'SUCCESS') {
      hide();
      message.success('更新成功');
      return true;
    } else {
      hide();
      message.success(rsp.msg);
      return false;
    }
  } catch (error) {
    hide();
    message.error('更新失败');
    return false;
  }
};

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>(null);
  const [dateRange, setDateRange] = useState<any>();
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const [requestStatus] = useState(currentUser?.userInfo?.role !== 'super');
  const [upAdmin] = useState(currentUser?.userInfo?.role !== 'normal');
  const [commandType] = useState(currentUser?.userInfo?.commandType);
  const [commandVisible, handleCommandVisible] = useState(false);
  const [currentRow, setCurrentRow] = useState({});
  const [commandFormType, setCommandFormType] = useState(0);
  const [currentPromoteRow, setCurrentPromoteRow] = useState({});
  const [promoteVisible, setPromoteVisible] = useState(false);
  const [commandDetail, setCommandDetail] = useState({});
  const [copyCommandVisible, setCopyCommandVisible] = useState<any>(false);
  const [dealCateVisible, handleDealCateVisible] = useState<boolean>(false);
  const [keyword, setKeyword] = useState('');
  const [timeType, setTimeType] = useState<number>(1);
  const [commands, setCommands] = useState([]);
  const [cates, setCates] = useState([]);
  const cpsConf = [
    {
      label: 'APP_2',
      value: 'CPS-ZBJ-yf2',
    },
    {
      label: 'APP_3',
      value: 'CPS-ZBJ-yf3',
    },
    {
      label: 'APP_4',
      value: 'CPS-ZBJ-yf4',
    },
    {
      label: 'APP_5',
      value: 'CPS-ZBJ-yf5',
    },
    {
      label: 'APP_6',
      value: 'CPS-ZBJ-yf6',
    },
    {
      label: 'APP_7',
      value: 'CPS-ZBJ-yf7',
    },
  ];
  const commandTypes = [
    {
      label: '手动',
      value: 2,
    },
    {
      label: '自动',
      value: 1,
    },
  ];
  let rateTypes = [
    {
      label: '保量',
      value: 1,
    },
    {
      label: '正常',
      value: 2,
    },
  ];
  const TimeTypes = [
    {
      label: '按失效时间',
      value: 0,
    },
    {
      label: '按创建时间',
      value: 1,
    },
  ];
  const commandStatus = {
    1: {
      text: '使用中',
      status: 'Success',
    },
    0: {
      text: '已下线',
      status: 'Error',
    },
  };
  const handleShowDeleteCommand = (record: any) => {
    Modal.confirm({
      title: `删除：${record.shopName} 口令`,
      content: (
        <div>
          <p>商品名称：`{record.productName}`</p>
          <p>佣金比例： `{record.rate / 100}%`</p>
        </div>
      ),
      okText: '确定删除',
      onOk: async () => {
        const rsp = await deleteDyCommand(record);
        if (rsp.code === 'SUCCESS') {
          if (rsp.data === 1) {
            message.success('删除成功');
            if (actionRef.current) {
              actionRef.current.reload();
            }
          } else {
            message.error('删除失败');
          }
        }
      },
    });
  };
  const columns: ProColumns<any>[] = [
    {
      title: '媒体APP',
      dataIndex: 'cps',
      valueType: 'checkbox',
      hideInTable: true,
      initialValue: ['CPS-ZBJ-yf2'],
      hideInSearch: requestStatus,
      request: async () => {
        return cpsConf;
      },
    },

    {
      title: '佣金类型',
      dataIndex: 'rateType',
      valueType: 'select',
      hideInTable: true,
      hideInSearch: !upAdmin,
      request: async () => {
        return !requestStatus
          ? [
              ...rateTypes,
              {
                label: '后台',
                value: 3,
              },
            ]
          : rateTypes;
      },
    },
    {
      title: '关键词',
      dataIndex: 'keyword',
      hideInTable: true,
      fieldProps: {
        onInput: (e) => {
          setKeyword(e.target.value);
        },
      },
    },
    {
      title: '直播间信息',
      dataIndex: 'shopName',
      copyable: true,
      width: 100,
      render: (_) => <a>{_}</a>,
    },
    {
      title: '产品类型',
      dataIndex: 'cate',
      valueType: 'select',
      request: async () => {
        const rsp = await getStoreCate();
        setCates(rsp.data);
        return rsp.data;
      },
    },
    {
      title: '商品名称',
      dataIndex: 'productName',
      copyable: true,
    },
    {
      title: '商品图片',
      dataIndex: 'imgUrl',
      hideInSearch: true,
      valueType: 'image',
    },
    {
      title: '单价',
      dataIndex: 'price',
      hideInSearch: true,
    },
    {
      title: '命令类型',
      dataIndex: 'commandType',
      valueType: 'select',
      hideInSearch: requestStatus,
      hideInTable: requestStatus,

      request: async () => {
        return commandTypes;
      },
    },
    {
      title: '口令状态',
      dataIndex: 'status',
      valueType: 'select',
      hideInSearch: requestStatus,
      valueEnum: commandStatus,
    },
    {
      title: '渠道',
      dataIndex: 'extData',
      hideInSearch: true,
      hideInTable: requestStatus,
    },
    {
      title: '后台比例',
      dataIndex: 'rate',
      width: 50,
      hideInSearch: true,
      sorter: (a, b) => a.rate - b.rate,
      hideInTable: requestStatus,
      renderText(text) {
        return text / 100 + '%';
      },
    },

    {
      title: '佣金比例',
      dataIndex: 'subRate',
      sorter: (a, b) => a.disRate - b.disRate,
      width: 50,
      renderText(text) {
        return text / 100 + '%';
      },
      fieldProps: {
        onInput: (e) => {
          setKeyword(`佣金：${e.target.value}%`);
        },
      },
      fieldProps: {
        onInput: (e) =>{
          setKeyword(`佣金：${e.target.value}%`)
        }
      }
    },
    {
      title: '保量比例',
      dataIndex: 'qualityRate',
      hideInSearch: true,
      hideInTable: commandType===2,
      width: 50,
      renderText(text) {
        return text / 100 + '%';
      },
    },

    {
      title: '小程序链接',
      dataIndex: 'wxCommand',
      copyable: true,
    },
    {
      title: '创建时间',
      dataIndex: 'startTime',
      hideInSearch: true,
      width: 100,
      copyable: true,
      valueType: 'dateTime',
    },
    {
      title: '订单查询时间类型',
      dataIndex: 'timeType',
      valueType: 'select',
      hideInTable: true,
      request: async () => {
        return TimeTypes;
      },
      fieldProps: {
        value: timeType,
        onChange: (val) => {
          setTimeType(val);
        },
      },
    },
    {
      title: '失效时间',
      dataIndex: 'endTime',
      hideInSearch: true,
      width: 100,
      copyable: true,
      valueType: 'dateTime',
    },
    {
      title: '口令创建时间',
      dataIndex: 'orderDate',
      valueType: 'dateRange',
      hideInForm: true,
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            startTime: value[0],
            endTime: value[1],
          };
        },
        fieldProps: {
          value: dateRange,
          onChange: (value: any) => {
            if (value && value.length === 2) {
              setDateRange(value);
            }
          },
        },
      },
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      align: 'center',
      hideInTable: requestStatus,
      render: (text, record) => [
        <>
          <a
            key="getCommand"
            onClick={async () => {
              setCommandDetail(record);
              setCopyCommandVisible(true);
            }}
          >
            获取分享口令
          </a>
          ,
          <a
            key="editable"
            onClick={async () => {
              setCurrentRow(record);
              setCommandFormType(1);
              handleCommandVisible(true);
            }}
          >
            编辑
          </a>
          ,
          <a
            key="delete"
            onClick={async () => {
              handleShowDeleteCommand(record);
            }}
          >
            删除
          </a>
          ,
          {record.delay === 0 ?
            <a
            key="delay"
            onClick={async () => {
               Modal.confirm({
                content: '是否延期当前口令',
                onOk: async () => {
                  const rsp = await delayCommandTime({id: record.id});
                  if(rsp.code === "SUCCESS") {
                    message.open({
                      type: 'success',
                      content: '提交成功'
                    })
                    if (actionRef.current) {
                      actionRef.current.reload();
                    }
                  } 
                },
              })
            }}
          >
            延期
          </a> : "已延期"
          }
        </>,
      ],
    },
  ];
  useEffect(() => {
    const startOfDay = new Date(new Date());
    startOfDay.setHours(0, 0, 0, 0);
    setDateRange([startOfDay, new Date()]);
  }, []);
  const generateFormattedText = async (data: any[]) => {
    return data
      .map((item) => {
        // 确定使用的比率
        const rate = item.qualityRate !== 0 ? item.qualityRate : item.subRate;
        // 转换为百分比（假设原始数据是4540表示45.4%）
        const percentage = (rate / 100).toFixed(0) + '%';

        return {
          rate,
          text: `🔥${item.shopName} ${percentage}\n失效时间：${item.endTime}\n${item.url}\n`,
        };
      })
      .sort((a, b) => b.rate - a.rate) // 按rate从大到小排序
      .map((item) => item.text) // 提取排序后的文本
      .join('\n'); // 用换行分隔每个条目
  };
  const copyToClipboard = async (text: string) => {
    try {
      // 现代API
      if (navigator.clipboard?.writeText) {
        await navigator.clipboard.writeText(text);
      } else {
        // 降级方案
        const textarea = document.createElement('textarea');
        textarea.value = text;
        textarea.setAttribute('readonly', '');
        textarea.style.position = 'absolute';
        textarea.style.left = '-9999px';
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
      }
      message.success('复制成功');
      setKeyword('');
      return true;
    } catch (err) {
      message.error('复制失败:');
      return false;
    }
  };
  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        headerTitle={'全部口令'}
        actionRef={actionRef}
        rowKey="id"
        scroll={{ x: '1100px' }}
        toolBarRender={() => [
          !requestStatus ? (
            <>
              <Button
                key="2"
                type="primary"
                onClick={() => {
                  handleDealCateVisible(true);
                }}
              >
                处理分类
              </Button>
              <Button
                key="23"
                type="primary"
                onClick={() => {
                  setCurrentRow({});
                  setCommandFormType(0);
                  handleCommandVisible(true);
                }}
              >
                创建口令
              </Button>
              <Button
                key="23"
                type="primary"
                onClick={async() => {
                  const text = await generateFormattedText(commands);
                  await copyToClipboard(`💗 ${keyword}合集 💗 \n${text}`);
                }}
              >
                复制合集
              </Button>
            </>
          ) : (
            <Button
              key="editable"
              type="primary"
              onClick={async () => {
                setCurrentPromoteRow({});
                setPromoteVisible(true);
              }}
            >
              推广
            </Button>
          )

      ]}
        search={{
          defaultCollapsed: false,
          labelWidth: 120,
          optionRender: ({ searchText, resetText }, { form }) => {
            return [
              <Button
                key="reset"
                style={{ marginRight: '10px' }}
                onClick={() => {
                  actionRef?.current?.reset();
                }}
              >
                {resetText}
              </Button>,
              <Button key="search" type="primary" htmlType="submit" style={{ marginRight: '10px' }}>
                {searchText}
              </Button>,
              // requestStatus ?  '' :
              <Button
                key="export"
                type="primary"
                onClick={async() => {
                  const hide = message.loading('正在导出');
                  const defaultValues = columns.reduce((acc:any, column:any) => {
                    if (column.fieldProps && column.fieldProps.value !== undefined) {
                      acc[column.dataIndex] = column.fieldProps.value;
                    }
                    return acc;
                  }, {});

                  const startTime = moment(new Date(dateRange[0])).format('YYYY-MM-DD HH:mm:ss');
                  const xlsTime = moment(new Date(dateRange[0])).format('YYYY-MM-DD');
                  const endTime = moment(new Date(dateRange[1]).setHours(23,59,59,0)).format('YYYY-MM-DD HH:mm:ss');
                  const fieldData = form.getFieldsValue();
                  let params = {
                    ...fieldData,
                    ...defaultValues,
                    dataType: 'export',
                    startTime,
                    endTime,
                  };
                const rsp = await dyCpsCommands(params);
                if (rsp.code === 'SUCCESS') {
                  let dataToExport = [];
                  let createTimeColIndex = 8; // 对应 '创建时间'
                  let expireTimeColIndex = 9; // 对应 '失效时间'
                 let result = rsp.data.data.reduce((acc, item) => {
                    // 生成一个唯一键，代表 shopName 和 subRate 的组合
                    const uniqueKey = `${item.shopName}_${item.subRate}`;
                    
                    // 如果这个键还没有被记录过，则说明是第一次遇到这个组合
                    if (!acc.seen[uniqueKey]) {
                      acc.seen[uniqueKey] = true; // 标记这个组合为已见
                      acc.result.push(item); // 将当前项放入结果数组
                    }
                    return acc;
                  }, { seen: {}, result: [] }) // 初始化累加器：一个空对象用于记录，一个空数组用于存放结果
                  .result ;// 最后从累加器中提取结果数组
                  dataToExport=result.map(item => ({
                    '直播间': item.shopName,
                    '商品名称': item.productName,
                    '分类':  cates.find(entry => entry.value === item.cate)?.label ?? '未知',
                    '渠道': item.extData,
                    '后台比例': item.rate/100+'%',
                    '散单比例': item.subRate/100+'%',
                    '保量比例': item.qualityRate/100+'%',
                    '微信口令': item.wxCommand,
                    '创建时间': formatDateForExport(item.startTime),
                    '失效时间': formatDateForExport(item.endTime),
                    // 确保字段名与Excel表头匹配
                  }));
                  if(currentUser?.userInfo?.role === 'admin') {
                    if(currentUser?.userInfo?.commandType===1) {
                       createTimeColIndex = 6; // 对应 '创建时间'
                       expireTimeColIndex = 7; //
                    } else {
                      createTimeColIndex = 5; // 对应 '创建时间'
                      expireTimeColIndex = 6; //
                    }
                   
                    dataToExport=result.map(item => ({
                      '直播间': item.shopName,
                      '商品名称': item.productName,
                      '分类':  cates.find(entry => entry.value === item.cate)?.label ?? '未知',
                      '佣金比例': item.subRate/100+'%',
                      ...(currentUser?.userInfo?.commandType===1 ? {'保量比例': item.qualityRate/100+'%'} : {}),
                      '微信口令': item.wxCommand,
                      '创建时间': formatDateForExport(item.startTime),
                      '失效时间': formatDateForExport(item.endTime),
                      // 确保字段名与Excel表头匹配
                    }));
                  } 
                  const worksheet = XLSX.utils.json_to_sheet(dataToExport);
                  

                  // 获取 worksheet 的引用范围
                  const range = XLSX.utils.decode_range(worksheet['!ref']);

                  // 遍历行（从第 2 行开始，第 1 行通常是表头）
                  for (let R = range.s.r + 1; R <= range.e.r; R++) {
                      // 处理 '创建时间' 列
                      const createTimeCellRef = XLSX.utils.encode_cell({r: R, c: createTimeColIndex});
                      // 如果该单元格存在
                      if (worksheet[createTimeCellRef]) {
                          // v 可以保持格式化字符串，但设置 t 为 'd' 表示日期，并设置 z 格式
                          worksheet[createTimeCellRef].t = 'd'; // 数据类型为 Date
                          worksheet[createTimeCellRef].z = 'yyyy-mm-dd hh:mm:ss'; // 指定日期时间格式
                      }

                      // 处理 '失效时间' 列
                      const expireTimeCellRef = XLSX.utils.encode_cell({r: R, c: expireTimeColIndex});
                      if (worksheet[expireTimeCellRef]) {
                          worksheet[expireTimeCellRef].t = 'd';
                          worksheet[expireTimeCellRef].z = 'yyyy-mm-dd hh:mm:ss';
                      }
                  }
                  const workbook = XLSX.utils.book_new();
                  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
                  XLSX.writeFile(workbook, `口令-${xlsTime}.xlsx`);
                  hide();
                }
                }}
              >
                导出
              </Button>,
            ];
          },
        }}
        request={async (params: any) => {
          const defaultValues = columns.reduce((acc: any, column: any) => {
            if (column.fieldProps && column.fieldProps.value !== undefined) {
              acc[column.dataIndex] = column.fieldProps.value;
            }
            return acc;
          }, {});

          const startTime = moment(new Date(dateRange[0])).format('YYYY-MM-DD HH:mm:ss');
          const endTime = moment(new Date(dateRange[1]).setHours(23, 59, 59, 0)).format(
            'YYYY-MM-DD HH:mm:ss',
          );

          // 将默认值合并到请求参数中
          const data = { ...params, ...defaultValues, startTime, endTime };

          const rsp = await dyCpsCommands(data);
          if (rsp.code === 'SUCCESS') {
            setCommands(rsp.data.data);
            console.log(JSON.stringify(rsp.data.data));
            return {
              data: rsp.data.data,
              total: rsp.data.total,
            };
          }
        }}
        columns={columns}
      />
      <CommandDrawer
        onSubmit={async (value) => {
          // console.log(value)
          // return;
          const success = await handleSaveCommand({ ...value });
          if (success) {
            handleCommandVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          setCurrentRow({});
          handleCommandVisible(false);
        }}
        updateModalVisible={commandVisible}
        values={currentRow || {}}
        formType={commandFormType}
      />
      <CopyCommandForm
        onSubmit={async (value) => {
          if (value) {
            message.success('复制成功~');
          } else {
            message.error('复制失败~');
          }
          setCopyCommandVisible(false);
        }}
        onCancel={() => {
          setCopyCommandVisible(false);
        }}
        updateModalVisible={copyCommandVisible}
        values={commandDetail || {}}
      />
      <PromoteDrawer
        onSubmit={async (value) => {
          const success = await saveSubChannelPercent({ ...value });
          if (success) {
            setPromoteVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          setPromoteVisible(false);
        }}
        updateModalVisible={promoteVisible}
        values={currentPromoteRow || {}}
        formType={commandFormType}
      />
      <EditCateForm
        onSubmit={async (value) => {
          console.log(value);
          // return;
          const rsp = await saveStoreCate({ ...value });
          if (rsp.code === 'SUCCESS') {
            setPromoteVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleDealCateVisible(false);
        }}
        updateModalVisible={dealCateVisible}
        values={currentPromoteRow || {}}
      />
    </PageContainer>
  );
};
export default TableList;
